<?php
	require '../../include/library.inc.php';
	require '../../include/admin_login.inc.php';
	
	$sql_lang = 'SELECT lang_id,Name,code FROM language WHERE published ';

	if (!isset($_POST['is_submitted'])) {
		$_POST['is_submitted'] = '';
	}
	
	if (!isset($error_message)) {
		$error_message = '';
	}	


if($_POST["redirect"] || $_SESSION['redirect'] ){
	if($_POST["redirect"]) $redirect = $_POST["redirect"];
	if($_SESSION['redirect']){ 
	$redirect = $_SESSION['redirect'];
	unset($_SESSION['redirect']);
	}
}else{
       $redirect = $_SERVER['HTTP_REFERER'];	
     }	
	 	
	if ($_POST['is_submitted']) {
		
		$error_message = '';
		$redirect = $_POST["redirect"];
    
	
	$result_lang = query($sql_lang);
	while ($row_lang = mysql_fetch_object($result_lang)) {
	
		if (!$_POST['title'][$row_lang->lang_id])  $error_message .= 'Не е въведено заглавие на '.$row_lang->Name.'<br/>';
		
		
		if (!$_POST['sef_url'][$row_lang->lang_id])
		{
			$error_message .= 'Не е въведен SEF URL на '.$row_lang->Name.'<br/>';
		}else{
			
		 if(!preg_match('/^[0-9A-Za-z\p{Cyrillic}\-\_]+$/u', $_POST['sef_url'][$row_lang->lang_id])) 						            $error_message .= 'Въведеният SEF URL е невалиден<br/>';
			$sql = "SELECT id FROM sef_url WHERE sef_url = '".$_POST['sef_url'][$row_lang->lang_id]."' ";
			$result = query($sql);
			if ($row_seo = mysql_fetch_object($result)) $error_message .= 'Въведеният SEF URL на '.$row_lang->Name.' вече е използван<br/>';
		}
	
	}
	
	
	
    if(!$error_message) {
		
		
		$sql = 'SELECT MAX(order_number)+1 AS order_number FROM projects';
		$row_number = mysql_fetch_assoc(query($sql));
		
		//Създаваме проекта
		$sql = "INSERT INTO projects
				  (published, order_number, url, color)
				VALUES
				  ('".intval($_POST['published'])."', '".$row_number['order_number']."', 
				   '".escape($_POST['url'])."','".$_POST['color']."')";
		query($sql);
		$id = mysql_insert_id();
		
		$result_lang = query($sql_lang);
		while ($row_lang = mysql_fetch_object($result_lang)) {
			
			$sql = "INSERT INTO project_description
				  (project_id, lang_id, title, description, meta_key, meta_description)
				VALUES
				  ('".$id."',
				  '".$row_lang->lang_id."', 
				  '".escape($_POST['title'][$row_lang->lang_id])."', 
				  '".escape($_POST['description'][$row_lang->lang_id])."', 
				  '".escape($_POST['meta_key'][$row_lang->lang_id])."',
				  '".escape($_POST['meta_description'][$row_lang->lang_id])."')";
				 
			query($sql);
			
			$sql = "SELECT id FROM sef_url WHERE sef_url = '".$_POST['sef_url'][$row_lang->lang_id]."' ";
			$sql = "INSERT INTO sef_url
				  ( lang_id, tamplate, query, sef_url)
				VALUES
				  ('".$row_lang->lang_id."', 
				  'project', 
				  '".$id."',
				  '".$_POST['sef_url'][$row_lang->lang_id]."')";
				 
			query($sql);
		}
		
		
		$upload_path = "../project_images/covers/";
		if (is_uploaded_file($_FILES['cover']['tmp_name'])) {
			$tmp_file = $_FILES['cover']['tmp_name'];
			$exp = explode('.',$_FILES['cover']['name']);
			$img_type = strtolower(end($exp));
			$new_name = $_POST['sef_url'][2]."_cover.".$img_type;
			
			if(move_uploaded_file($tmp_file, $upload_path.$new_name)) {
				
				$sql = "UPDATE projects SET
							cover = '$new_name'
						WHERE project_id = '$id'";
				query($sql);
				
			} else{
				$_SESSION['message'] .= 'Грешка при качване на корицата. ';
			}
		}
		
		
		$upload_path = "../project_images/thumps/";
		if (is_uploaded_file($_FILES['thump']['tmp_name'])) {
			$tmp_file = $_FILES['thump']['tmp_name'];
			$exp = explode('.',$_FILES['thump']['name']);
			$img_type = strtolower(end($exp));
			$new_name = $_POST['sef_url'][2]."_thump.".$img_type;
			
			if(move_uploaded_file($tmp_file, $upload_path.$new_name)) {
				
				$sql = "UPDATE projects SET
							thump = '$new_name'
						WHERE project_id = '$id'";
				query($sql);
				
			} else{
				$_SESSION['message'] .= 'Грешка при качване на малката снимка. ';
			}
		}
		
		
		if($_POST['category_id'])
		{
			$category_id = $_POST['category_id'];
		  
			foreach ($category_id as $key => $value) {
			
				$sql = 'INSERT INTO project_to_category
							  (project_id,category_id)
							VALUES
							  ('.$id.','.intval($value).')
							  ';
				query($sql);
			
			}
		}
		
		
		
		
		$_SESSION['message'] .= 'Проектът е добавен успешно!';
         if($_POST["redirectForm"]){
           redirect($_POST["redirectForm"]);
		}else{
			$_SESSION['redirect'] = $redirect;
		   redirect(HTML_BASE_ADMIN.'/project_edit.php?project_id='.$id);
		   
		   
		}
		
    }

}
  	
	
	head_admin("Нов проект");
?>

		
            <?php if ($error_message) { ?>
			<div class="message red">
				<h3>Грешка!</h3>
				<?=$error_message?>
			</div>
			<?php } ?>
            
             <?php if ($_SESSION['message']) { ?>
    		<div class="message green">
       			 <?=$_SESSION['message']?>
    		</div>
			<?php unset($_SESSION['message']); } ?>
			
            <div class="topbuttons">
            	<a href="<?=$redirect?>">Обратно</a>
            </div>
			
            <h3>Създаване на нова страница</h3>
			            
            <form id="project_new_form_id" action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
            <input type="hidden" name="is_submitted" value="1" />
			<input type="hidden" name="redirect" value="<?=$redirect?>" />
             <input id="redirectForm" type="hidden" name="redirectForm" value="" />
            <input type="hidden" name="redirect" value="<?=$redirect?>" />						
					
			
		
	<div id="tabs">
   
        
        	<ul id="tabs-ui">
           
			</ul>
			
			
			<?php
			$tabs="";
			$result_lang = query($sql_lang);
			while ($row_lang = mysql_fetch_object($result_lang)) {
				
		     $tabs.=' <li><a href="'.$_SERVER['PHP_SELF'].'#tabs-'.$row_lang->lang_id.'">'.$row_lang->Name.'</a></li>';					  
			?>
           
		<div id="tabs-<?=$row_lang->lang_id?>">
           
                <h3>Данни на  <?=$row_lang->Name?></h3>
                
                <dt><label class="required">Линк <?=$row_lang->Name?>:</label>
        <?=HTML_BASE?><input class="sef_url" id="sef_url_<?=$row_lang->lang_id?>"  name="sef_url[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['sef_url'][$row_lang->lang_id]?>" >
        </dt>	
                
                
                <dt><label class="required">Заглавие на <?=$row_lang->Name?></label></dt>
                <dd><input class="inputbox w500" id="title_<?=$row_lang->lang_id?>" name="title[<?=$row_lang->lang_id?>]" type="text" value="<?=$_POST['title'][$row_lang->lang_id]?>" ></dd>
                 
                <dt><label >Мета описание на <?=$row_lang->Name?>(до 110 символа)</label></dt>
                <dd><textarea class="inputbox w500" name="meta_description[<?=$row_lang->lang_id?>]" rows="3" maxlength="110"><?=$_POST['meta_description'][$row_lang->lang_id]?></textarea></dd>
                
                <dt><label >Ключови думи на <?=$row_lang->Name?>(до 110 символа)</label></dt>
                <dd><textarea class="inputbox w500" name="meta_key[<?=$row_lang->lang_id?>]" rows="3" maxlength="110"><?=$_POST['meta_key'][$row_lang->lang_id]?></textarea></dd>
			
            			
		   
                     <script>
					 	
						$("#title_<?=$row_lang->lang_id?>").keyup(function(){
							
							$("#sef_url_<?=$row_lang->lang_id?>").val(convertToSlug($(this).val()));
						});
						$("#sef_url_<?=$row_lang->lang_id?>").keyup(function(){
							
							$("#sef_url_<?=$row_lang->lang_id?>").val(convertToSlug($(this).val()));
						});
					 </script>
            
           </div>
            
           <?php
				
			}
			
	  		?>
          
           </div>
           
           
           
			<dl class="clearfix" >
            
            
            	<dt>
                    <label class="required">Снимка на проекта
                    </label>
                </dt>
                <dd>
                    <input class="inputbox w250" name="thump" type="file" accept="image/*" />
                </dd>
                
                
                <dt>
                    <label class="required">Корица на проекта (<?=PROJECT_COVER_WIDTH?> на <?=PROJECT_COVER_HEIGHT?> px)
                    </label>
                </dt>
                <dd>
                    <input class="inputbox w250" name="cover" type="file" accept="image/*" />
                </dd>
            
            	<dt><label class="required">#Основен цвят:</label></dt>
            	<dd><input   name="color" type="color" value="<?=$_POST['color']?>" ></dd>
           		
                <dt><label >URL:</label></dt>
            	<dd><input class="inputbox w250"  name="url" type="text" value="<?=$_POST['url']?>" ></dd>
            </dl>
            
           <dl>
   			<dt>
      			<label >Категория</label>
    		</dt>
    		<dd>
				<ul class="type-box">
				<?php         
                    $sql_c = "SELECT
                    c.category_id,
                    d.Name
                    
                FROM
                    category AS c,
                    category_description AS d
                WHERE
                
                    c.category_id = d.category_id
                    
                    AND
                    
                    d.lang_id = '1'
                    
                    AND
                    c.published
                    
                    ORDER BY c.order_number DESC
                    
                  ";
                
                    $result_c = query($sql_c);
                    $i = 1;	
                    while ($row = mysql_fetch_object($result_c)) {
                          ?>
                        <li>
                          <label>
                            <input class="checkbox" name="category_id[<?=$i?>]" type="checkbox" value="<?=$row->category_id?>" 
                                        <?=(($row->category_id == $_POST["category_id"][$i])?"checked=\"checked\"":"")?> />
                            <?=$row->Name?>
                          </label>
                        </li>
        			<?php $i++; } ?>
				</ul>
			</dd>
		</dl>
            
            
            
		<dl class="clearfix" >	
		
            
				<input class="checkbox" name="published" id="published" type="checkbox" value="1" <?=(($_POST['published'])?"checked=\"checked\"":"")?> />
				<label>Публикуван</label></dd>
            
           
		</dl>
						
			</form>  
          
          
  <script>
	$(document).ready(function(e) {
           $("#tabs-ui").html('<?=$tabs?>');
	       $( "#tabs" ).tabs();
	  
      });			
  </script>
  
            
<?php
	controls($redirect, "#project_new_form_id");
	foot_admin(); 
?>